;
(function() {
  'use strict';
  angular.module('services.usermanager.userServer', [])
    .factory('userData', userData)       //页面数据
    .factory('userRequest', userRequest) //请求url
    .factory('userCRUD', userCRUD)       //用户增删改查service
    .factory('getIds', getIds)           //获取checkbox的id
    .controller('addCtrl',addCtrl)       //新增用户Ctrl
    .controller('modifyCtrl',modifyCtrl);//修改用户Ctrl

  /**
    * [userData] 页面数据
   * @param $cookies
   * @returns {
   *   queryParam,
   *   ids,
   *   userIds,
   *   userNames,
   *   userNameString,
   *   queryResult
   * }
   */
  function userData($cookies) {
    return {
      queryParam: { //查询发送对象
        userId: $cookies.getObject('userCookie').userId,
        page: {
          currentPage: 1,
          pageSize: '10'
        },
        userName: '',
        realName: '',
        phone: '',
        roleId: ''
      },
      ids: [],    //checkbox中的id
      userIds: {  //id的字符串
        userIds: ''
      },
      userNames: [], //checkbox中的name
      userNameString: '', //name的字符串
      queryResult: { //查询结果
        userData: {},
        totalCount: 0,
        isQuery: false
      }
    };
  }
  userData.$inject = ['$cookies'];

  /**
    * [getIds] 获取用户ids
   * @param $cookies
   * @param userData
   * @returns {Function}
   */
  function getIds($cookies, userData) {
    return function(user) {
      var index;
      index = userData.ids.indexOf(user.userId);
      if (index === -1) {
        userData.ids.push(user.userId);
        userData.userNames.push(user.userName);
      } else {
        userData.ids.splice(index, 1);
        userData.userNames.splice(index, 1);
      }
      userData.userNameString = userData.userNames.join(',');
      userData.ids.length === 1 && angular.forEach(userData.queryResult.userData, function(role) {
        if (userData.ids[0] === role.userId) {
          $cookies.putObject('userMngInfo', role);
        }
      });
    };
  }
  getIds.$inject = ['$cookies', 'userData'];

  /**
    * [userCRUD] 增删改查service
   * @param userData
   * @param userRequest
   * @param CoreService
   * @param $mdDialog
   * @param $cookies
   * @returns {{addUserSave: addU, modifyUser: modifyU, deleteUser: deleteU, pwdReset: pwdR}}
   */
  function userCRUD(userData, userRequest, CoreService, $mdDialog, $cookies) {
    return {
      addUserSave: addU,
      modifyUser: modifyU,
      deleteUser: deleteU,
      pwdReset: pwdR
    };

    function addU(ev) {
      $mdDialog.show({
          controller: addCtrl,
          templateUrl: 'views/sysMng/userMng/form/add.html',
          targetEvent: ev,
        })
        .then(addSave);
    }

    function addSave(answer) {
      answer.expTime = CoreService.dateFormat(answer.expTime, 'yyyy-MM-dd hh:mm:ss');
      answer.userId = $cookies.getObject('userCookie').userId;
      answer.role = undefined;
      userRequest.addUserSave(answer, function(res) {
        if (res && res.state === '10000') {
          CoreService.dialog('用户保存成功！');
          userData.ids = [];
          userData.userNames = [];
          userRequest.userQuery();
        } else if (res && res.state === '10001') {
          CoreService.dialog('保存失败！');
        } else {
          CoreService.dialog('请求失败');
        }
      });
    }

    function modifyU(ev) {
      if (userData.ids.length === 1) {
        $mdDialog.show({
            controller: modifyCtrl,
            templateUrl: 'views/sysMng/userMng/form/modify.html',
            targetEvent: ev,
          })
          .then(modifyUser);
      } else if (userData.ids.length === 0) {
        CoreService.dialog('请选择要修改的用户！');
      } else {
        CoreService.dialog('请选择有且一个用户！');
      }
    }

    function modifyUser(answer) {
      answer.userId = userData.ids[0];
      answer.expTime = CoreService.dateFormat(answer.expTime, 'yyyy-MM-dd hh:mm:ss');
      answer.updateId = $cookies.getObject('userCookie').userId;
      answer.role = undefined;
      answer.roleName = undefined;
      answer.roleId = parseInt(answer.roleId);
      userRequest.updateSave(answer, function(res) {
        if (res.state === '10000') {
          CoreService.dialog('修改用户保存成功');
          userData.ids = [];
          userData.userNames = [];
          userRequest.userQuery();
        } else if (res && res.state === '10001') {
          CoreService.dialog('保存失败！');
        } else {
          CoreService.dialog('请求失败');
        }
      });
    }

    function deleteU(ev) {
      if (userData.ids.length === 0) {
        CoreService.dialog('至少选择一个用户！');
      } else {
        var confirm = $mdDialog.confirm()
          .title('警告')
          .content('删除用户' + userData.userNameString + '后,用户不可用,确定删除？')
          .ok('确定')
          .cancel('取消')
          .targetEvent(ev);
        $mdDialog.show(confirm).then(sureDel);
      }
    }

    function sureDel() {
      userData.userIds.userIds = userData.ids.join(',');
      userData.userIds.userId = $cookies.getObject('userCookie').userId;
      userRequest.delUser(userData.userIds, function(result) {
        if (result && result.state === '10001') {
          CoreService.dialog('删除失败！');
        } else if (result && result.state === '10007') {
          var userName = result.data.join(',');
          CoreService.dialog('用户' + userName + '正在使用中不能删除！');
        } else if (result && result.state === '10000') {
          CoreService.dialog('删除成功！');
          userData.ids = [];
          userData.userNames = [];
          userRequest.userQuery();
        } else {
          CoreService.dialog('请求失败');
        }
      });
    }

    function pwdR() {
      if (userData.ids.length === 0) {
        CoreService.dialog('请至少选择一个用户');
      } else {
        var confirm = $mdDialog.confirm()
          .title('警告')
          .content('确定要重置用户' + userData.userNameString + '的密码吗？')
          .ok('确定')
          .cancel('取消');
        $mdDialog.show(confirm).then(sureReset);
      }
    }

    function sureReset() {
      userData.userIds.userIds = userData.ids.join(',');
      userData.userIds.userId = $cookies.getObject('userCookie').userId;
      userRequest.pwdReset(userData.userIds, function(result) {
        if (result.state === '10001') {
          CoreService.dialog('重置密码失败！');
        } else if (result.state === '10000') {
          CoreService.dialog('重置密码成功！');
          userData.ids = [];
          userData.userNames = [];
          userRequest.userQuery();
        } else {
          CoreService.dialog('请求失败');
        }
      });
    }

  }
  userCRUD.$inject = ['userData', 'userRequest', 'CoreService', '$mdDialog', '$cookies'];

  /**
    * [userRequest] 用户请求
   * @param Restangular
   * @param userData
   * @param CoreService
   * @param $cookies
   * @param CoreLoading
   * @returns {{userQuery: Function, roleQuery: Function, pwdReset: Function, addUserSave: Function, updateSave: Function, delUser: Function, checkName: Function, checkIdCard: Function}}
   */
  function userRequest(Restangular, userData, CoreService, $cookies, CoreLoading) {
    return {
      /**
       * [query 查询初始化用户数据显示]
       * @type {[type]}
       */
      userQuery: function(params) {
        if (!params) {
          params = userData.queryParam;
        }
        params.userId = $cookies.getObject('userCookie').userId;
        CoreLoading.setState(true);
        Restangular.all('sas/sysMng/user/query').post(params).then(
          function(res) {
            if (res && res.state === '10000') {
              userData.queryResult.totalCount = res.page.totalCount;
               var lastPage = Math.ceil(userData.queryResult.totalCount / userData.queryParam.page.pageSize);
              if (userData.queryParam.page.currentPage > lastPage) {
                //userData.queryParam.page.currentPage = lastPage;
                var params = userData.queryParam;
                Restangular.all('sas/sysMng/user/query').post(params).then(function(res) {
                  if (res && res.state === '10000') {
                    userData.queryResult.userData = res.data;
                    userData.queryResult.totalCount = res.page.totalCount;
                    userData.queryResult.isQuery = true;
                    CoreLoading.setState(false);
                  } else {
                    CoreService.dialog(res.state);
                    CoreLoading.setState(false);
                  }
                });
              } else {
                userData.queryResult.userData = res.data;
                userData.queryResult.totalCount = res.page.totalCount;
                userData.queryResult.isQuery = true;
                CoreLoading.setState(false);
              }
            } else {
              CoreService.dialog(res.state);
              CoreLoading.setState(false);
            }

          });
        return userData;
      },
      /**
       * [roleQuery 下拉框角色查询]
       * @type {[type]}
       */
      roleQuery: function(callback) {
        Restangular.one('sas/sysMng/role/roleQuery').get().then(callback);
      },
      /**
       * [pwdReset 密码重置]
       * @type {[type]}
       */
      pwdReset: function(params, callback) {
        Restangular.all('sas/sysMng/user/pwdReset').post(params).then(callback);
      },
      /**
       * [addUserSave 增加用户保存按钮]
       * @type {[type]}
       */
      addUserSave: function(params, callback) {
        Restangular.all('sas/sysMng/user/add').post(params).then(callback);
      },
      /**
       * [updateSave 修改用户保存]
       * @param  {[type]}   params
       */
      updateSave: function(params, callback) {
        Restangular.all('sas/sysMng/user/update').post(params).then(callback);
      },
      /**
       * [delUser 批量删除用户]
       * @type {[type]}
       */
      delUser: function(params, callback) {
        Restangular.all('sas/sysMng/user/delete').post(params).then(callback);
      },
      /**
       * [checkName 检查用户名是否重复]
       * @return {[type]}
       */
      checkName: function(params, callback) {
        Restangular.all('sas/sysMng/user/checkName').post(params).then(callback);
      },
      /**
       * [checkIdCard 检查身份证号是否存在]
       * @return {[type]}            [description]
       */
      checkIdCard: function(params, callback) {
        Restangular.all('sas/sysMng/user/checkIdCard').post(params).then(callback);
      },
      getRoles: function(callback) {
          Restangular.one('sas/sysMng/role/getRole').get().then(callback);
      }
    };
  }
  userRequest.$inject = ['Restangular', 'userData', 'CoreService', '$cookies', 'CoreLoading'];

  /**
    *  [addCtrl] 新增用户mDialog弹出页面controller
   * @param $scope
   * @param $mdDialog
   * @param $timeout
   */
  function addCtrl($scope, $mdDialog, $timeout,userRequest) {
    // Add User Information [Ojbect]
    $scope.userInfo = {
      userName: '',
      realName: '',
      sex: '0',
      pwd: '',
      email: '',
      phone: '',
      idCard: '',
      userRemark: '',
      expTime: new Date()//Expiration Time
    };

    //time not less than the current date
    // $scope.$watch('userInfo.expTime', function(newValue) {
    //   if (newValue && newValue < new Date()) {
    //     var now = new Date();
    //     $scope.userInfo.expTime = new Date(now.valueOf() + 86400000*7);
    //   }
    // },true);

    /**
     * [loadRoles Roles pull down]
     * @return {[type]} [function]
     */
    $scope.loadRoles = function() {
        $scope.roleInfos = [];
        return $timeout(function() {
            userRequest.getRoles(function(res){
                $scope.roleInfos = res.data;
            });
/*          $scope.roleInfos = [
          {roleId:'9', roleName:'普通用户'},
           {roleId:'1', roleName:'系统管理员'},
           {roleId:'2', roleName:'管理员', parentRole:'1'},
           {roleId:'3', roleName:'维护管理员',parentRole:'2'},
           {roleId:'4', roleName:'财务管理员', parentRole:'2'},
           {roleId:'5', roleName:'逗比管理员', parentRole:'3' },
           {roleId:'6', roleName:'神兽管理员', parentRole:'4' }
          ];*/
        }, 650);
      };

    /**
     * [cancel Turn Off]
     * @return {[type]} [function]
     */
    $scope.cancel = function() {
      $mdDialog.cancel();
    };

     /**
     * [queding save]
     * @param  {[obj]} answer [Form infomation object]
     * @return {[type]}       [function]
     */
    $scope.queding = function(answer) {
      if($scope.addForm.$invalid === undefined || $scope.addForm.$invalid){ //if form invalid ,not submitted
        return;
      }
      answer.roleId = answer.role.roleId;
      $mdDialog.hide(answer);
    };
  }
  addCtrl.$inject = ['$scope', '$mdDialog', '$timeout','userRequest'];

  /**
    * [addCtrl] 修改用户mDialog弹出页面controller
   * @param $scope
   * @param $mdDialog
   * @param $timeout
   * @param $cookies
   * @param userRequest
   */
  function modifyCtrl($scope, $mdDialog, $timeout,$cookies,userRequest) {
    // Modify user information object
    $scope.userInfo = {
      userId:'',
      userName: '',
      realName: '',
      sex: '0',
      email: '',
      phone: '',
      idCard: '',
      userRemark: '',
      expTime: null //Expiration Time
    };
    $scope.userInfo = $cookies.getObject('userMngInfo');
    //The following two lines of code to format date
    var expTime = $scope.userInfo.expTime && $scope.userInfo.expTime.replace(/-/g, '/');
    $scope.userInfo.expTime = new Date(expTime);

    //static data
    $scope.notSend = {
      uName : $scope.userInfo.userName,
      PPWD : '********'
    };

    /**
     * [loadRoles Roles pull down]
     * @return {[type]} [function]
     */
    $scope.loadRoles = function() {
        $scope.roleInfos = [];
        return $timeout(function() {
            userRequest.getRoles(function(res){
                $scope.roleInfos = res.data;
            });
//          $scope.roleInfos = [
//          {roleId:'9', roleName:'普通用户'}
           // {roleId:'1', roleName:'系统管理员'},
           // {roleId:'2', roleName:'管理员', parentRole:'1'},
           // {roleId:'3', roleName:'维护管理员',parentRole:'2'},
           // {roleId:'4', roleName:'财务管理员', parentRole:'2'},
           // {roleId:'5', roleName:'逗比管理员', parentRole:'3' },
           // {roleId:'6', roleName:'神兽管理员', parentRole:'4' }
//          ];
        }, 650);
      };

    /**
     * [cancel Turn Off]
     * @return {[type]} [function]
     */
    $scope.cancel = function() {
      $mdDialog.cancel();
    };

    /**
     * [queding save]
     * @param  {[obj]} answer [Form infomation object]
     * @return {[type]}        [function]
     */
    $scope.queding = function(answer) {
      if($scope.modifyForm.$invalid === undefined || $scope.modifyForm.$invalid){ //if form invalid ,not submitted
        return;
      }
      $mdDialog.hide(answer);
    };
  }
  modifyCtrl.$inject = ['$scope', '$mdDialog', '$timeout','$cookies','userRequest'];

})();